'use strict'
var sha1 = require('sha1');
var getRawBody = require('raw-body');
var Wechat = require('./wechat');
var util = require('./util');

module.exports = function (opts,handler) {
    var wechat = new Wechat(opts);//我们实例化一下Wechat，就可以在中间件中直接调用了

    return function *(next) {
        var that = this;
        //console.log(this.query);
        var token = opts.token;
        var signature = this.query.signature;
        var nonce = this.query.nonce;
        var timestamp = this.query.timestamp;
        var echostr = this.query.echostr;
        var str = [token, timestamp, nonce].sort().join('');
        var sha = sha1(str);



        if(this.method === 'GET'){
        	if (sha === signature) {
            	this.body = echostr + '';
        	}
        	else {
            	this.body = 'wrong';
        	}
        }else if(this.method === 'POST'){
        	if (sha !== signature) {
            	this.body = 'wrong';

            	return false;
        	}

        	var data = yield getRawBody(this.req,{
        		length: this.length,
        		limit: '1mb',
        		encoding: this.charset
        	})

        	//console.log(data.toString()) 
  // parseXMLAsync 是为了把 XML 解析为 JS 对象
        	var content = yield util.parseXMLAsync(data);

        	//console.log(content);
 // formatMessage 是为了把 JS 对象解析为扁平的 JS 对象
        	var message = util.formatMessage(content.xml);

        	
            //console.log(message);

            this.weixin = message;

            yield handler.call(this,next);   //转到业务层逻辑

            wechat.reply.call(this);  //真正回复
        }
        
    }
}